define(function (require, exports, module) {
    var myPub = require('./public');
    var integralSelet = require('./integral_selet');

    var smallImgArg300 = '?x-oss-process=style/goods_img_2';

    var oWindow = $(window);
    var oContain = $('.js_contain');   //内容
    var oHeader = $('.js_headerBox');   //头部
    var oIntegralFilter = $('.js_integralFilter');   //积分筛选部分
    var oIntegralUseIt = $('.js_integralUseIt');   // 积分抵扣使用提示
    var oSwiperUl = $('.js_sildeNavUl');      //swiper的头头
    var oSwiperCon = $('.js_swiper');         //swiper的内容
    var oScrollMain = $('.js_scrollMain');    //专区的盒子
    var oSlidePageWrap = $('.js_swiperWrap');
    var oSideBox = $('.js_sideBox');                // 侧边按钮框
    var oGoTop = $('.js_goTop');                    // 回到顶部

    var lazLoading = new myPub.lazLoadingImg();

    var firstData = [true,true,true];
    var resizeTimer = null ;    //

    var titArr = ["积分兑换","优惠购物","积分抵扣"];        //页面标题
    // 获取产品数据的路径
    var goodsDateUrl = [
        '/myInfo/getMemberGoods',
        '/myInfo/getCoMemberGoods',
        '/myInfo/getMemberDeductGoods'
    ];

    var integralGroup = integralSelet.setJSon;
    // console.log(integralGroup)

    // 获取积分筛选的数据
    integralSelet.GetSeletValue(function (val) {
        var index = parseInt(val.value);
        var startIntegral , endIntegral;
        // console.log("line near 38  index = " + index)
        switch (index){
            case 0:
                startIntegral = null;
                endIntegral = null;
                break;
            case 1:
                // console.log(" idnex = a  asdkgjlkg");
                startIntegral = 0;
                endIntegral = 999;
                break;
            case 2:
                startIntegral = 1000;
                endIntegral = 4999;
                break;
            case 3:
                startIntegral = 5000;
                endIntegral = 9999;
                break;
            case 4:
                startIntegral = 10000;
                endIntegral = 49999;
                break;
            case 5:
                startIntegral = 50000;
                endIntegral = null;
                break;
        }
        //保存当前swiper的筛选条件
        presentData.dataIndexArr[presentData.preNavIndex] = index;
        //保存当前筛选积分
        presentData.startIntegralArr[presentData.preNavIndex].startIntegral = startIntegral;
        presentData.endIntegralArr[presentData.preNavIndex].endIntegralArr = endIntegral;

        //将开始的数量清零
        presentData.startNum[presentData.preNavIndex] = 0;

        //点击之后数据就变过了
        firstData[presentData.preNavIndex] = false;

        //选择后想当于重新刷新，要还原请求的起始数据量
        presentData.startNum[presentData.preNavIndex] = 0;
        presentData.endNum[presentData.preNavIndex] = 0;
        //更新当前的数据，滚动的时候就能按最新的数据来加载
        // presentData.allAreaData[presentData.preNavIndex] = newDataGroup[index];
        // console.log(presentData.allAreaData[presentData.preNavIndex])
        //先清空数据列表
        $('.js_thisArea').eq(presentData.preNavIndex).find('.js_goodsList').empty();
        presentData.loadFinish[presentData.preNavIndex] = 0;
        //将滚动的盒子回到顶部
        $('.js_thisArea').eq(presentData.preNavIndex).stop().animate({scrollTop: '0'}, 250);
        //重新加载数据，填入数据列表
        // presentData.appendData(newDataGroup[index],presentData.preNavIndex)
        // console.log("line  near  88 " + goodsDateUrl[presentData.preNavIndex]);
        presentData.postAreaData(goodsDateUrl[presentData.preNavIndex],startIntegral,endIntegral,presentData.preNavIndex,index,function () {

        })
    });

    // integralSelet.setJSon
    // 回到过顶部
    oGoTop.on('click', function (e) {
        var oSlidePageScroll = $('.js_thisArea');
        oSlidePageScroll.eq(presentData.preNavIndex).stop().animate({scrollTop: '0'}, 250);
        oHeader.css({'top': 0}).find('.js_sildeNav').removeClass('active');
        e.stopPropagation();
    });

    module.exports= {
        init:function (data) {
            presentFn.init(true)
            presentFn.AppendSlidePage(titArr);
            presentFn.preSwiper(data);  //swiper

            //加载数据
            presentData.postAreaData(goodsDateUrl[0],presentData.startIntegralArr[presentData.preNavIndex].startIntegral,
                presentData.endIntegralArr[presentData.preNavIndex].endIntegral,presentData.preNavIndex,0,function () {

            });

            //页面滚动
            presentFn.scrollPage();

            // 历史记录初始化
            presentFn.HistoryInit();
            // 页面尺寸修改
            oWindow.on('resize',function() {
                if (resizeTimer) {
                    clearTimeout(resizeTimer)
                }
                resizeTimer = setTimeout(function(){
                    presentFn.init(true);
                }, 400);
            });
            // lazLoading.AddLazLoadingImg($('.js_scrollMain')[presentData.preNavIndex]);

            // 页面跳转记录数据
            // oWindow.unload(function(){
            //     presentFn.SetSession();
            // });
        }
    }



    //数据
    var presentData = {
        prePageArr: [],       //记录当前页
        preTabLoadOff: [],     //
        prePageSCroll: [],      //记录滚动高度
        preLoadFinish: [],      //
        startNum: [],              // 每个小类的开始加载数
        integIndex: 0,           //导航的索引
        endNum: [],                //  每个小类的结束加载数
        limitNum: 12,               // 每次加载的个数
        preNavIndex: 0,
        dataIndexArr: [0,0,0],         //保存当前筛选的索引
        allAreaData: [[],[],[]],       //全部数据1
        startIntegralArr: [{startIntegral: null},{startIntegral: null},{startIntegral: null}],   //积分筛选的开始积分
        endIntegralArr: [{endIntegral: null},{endIntegral: null},{endIntegral: null}],      //积分筛选的结束积分
        isIntegralArr: [1,1,0],      //是否显示积分筛选
        isIntegralUseIt: [0, 0, 1],  // 是否显示积分使用提示
        loadFinish: [0,0,0],         //是否已经加载完成
        isShowPoint: [true,true,false], // 价格是否显示积分

        postAreaData: function (url,startInteg,endInteg,index,dataIndex, fn) {
            var _this = this;
            // console.log("请求的数据为 " + url + " " + _this.startNum[index] + " " + _this.limitNum + " " + startInteg + " " + endInteg);
            if(_this.loadFinish[index] != 0){
                return;
            }
            G_JSON_POST(url,{
                limitNum: _this.limitNum,  //请求的条数
                startNum: _this.startNum[index],  //请求开始的条数
                startInteg: startInteg,  //积分范围 开始
                endInteg: endInteg       //积分范围 结束
            },function (data) {
                // console.log("返回的数据为  %o ", data);
                var thatData = data.obj;
                //如果startNum从0开始先清空数据列表内容
                var oHtml = "";
                if(_this.startNum[index] == 0){
                    //用于swiper滑的时候有没有加载过
                    _this.preTabLoadOff[index] = false;
                    //先显示积分筛选
                    if(_this.isIntegralArr[index] == 1){
                        oIntegralFilter.show();
                    }
                    if(_this.isIntegralUseIt[index] == 1){
                        oIntegralUseIt.show();
                    }
                    //如果请求回来是空的数据,展示
                    if(thatData.length == 0 && dataIndex == 0){
                        _this.allAreaData[index] = []
                        $('.js_moreBtnBox').eq(index).hide()
                        $('.js_thisArea').eq(index).append(presentFn.noProductHtml());
                        //如果全部的数据都为空的就要隐藏积分筛选栏
                        oIntegralFilter.hide();
                    }else if(thatData.length > 0){
                        _this.allAreaData[index] = thatData;
                        //先清空数据列表
                        $('.js_thisArea').eq(presentData.preNavIndex).find('.js_goodsList').empty();
                        oHtml = presentFn.presentHtml(thatData, 0, thatData.length,smallImgArg300,_this.isShowPoint[index]);
                        $('.js_scrollMain').eq(index).find('.js_goodsList').append(oHtml);
                        _this.startNum[index] = _this.limitNum + _this.startNum[index]
                    }
                }else {
                    if(thatData.length == 0){
                        //显示没有更多
                        $('.js_moreBtnBox').eq(index).find('.js_loadingBtn').hide().eq(0).show();
                    }else {
                        //追加到列表中
                        oHtml = presentFn.presentHtml(thatData, 0, thatData.length,smallImgArg300,_this.isShowPoint[index]);
                        $('.js_scrollMain').eq(index).find('.js_goodsList').append(oHtml);
                        _this.startNum[index] = _this.limitNum + _this.startNum[index];
                    }
                }
                myPub.SetImgHeight($('.js_scrollMain').eq(index).find('.js_goodsList'));
                lazLoading.DestroyLazLoadingImg();
                lazLoading.AddLazLoadingImg($('.js_thisArea')[index]);

                if(thatData.length < _this.limitNum){
                    //显示没有更多
                    $('.js_moreBtnBox').eq(index).find('.js_loadingBtn').hide().eq(0).show();
                    _this.loadFinish[index] = 1;
                }
            })
        }
    };

    var presentFn = {
        oSlidePageMain:'',
        nHeaderHeight: 0,
        time_Scroll: null,
        init:function (bOff) {
            if(bOff){
                oContain.css({
                    'padding-top': oHeader.outerHeight(true),
                });
                // myPub.SetImgHeight($('.js_goods_showTwo'));
                oIntegralFilter.css({
                    'top': oHeader.outerHeight(true)
                })
            }
        },

        // 插入slide
        AppendSlidePage: function (name) {
            for (var i = 0; i < name.length; i++) {
                oSlidePageWrap.append('<div class="swiper-slide js_scrollMain Height100"><section class="thisArea js_thisArea Height100"><div class="goods_showChangeBox active js_goods_showTwo js_swiperProList"><div class="goods_showChange"><ul class="goodsList clearfix js_goodsList"></ul></div><div class="moreBtnBox js_moreBtnBox"><p class="loadingBtn js_loadingBtn" style="display: none;"><a>没有更多</a></p><p class="loadingBtn js_loadingBtn"><span class="icon_loading icoStyle icon-spinner3 myRotateRefresh"></span><span>加载中</span></p></div></div></section></div>');
                // presentData.prePageArr.push(1);
                presentData.preTabLoadOff.push(true);
                presentData.prePageSCroll.push(0);
                // presentData.preLoadFinish.push(false)
                presentData.startNum.push(0)
                presentData.endNum.push(0)
            }
        },

        preSwiper:function (data) {
            var _this = this;
            _this.oSlidePageMain = oSwiperCon.swiper({
                pagination: oSwiperUl[0],
                // autoHeight: true,   //高度随内容变化
                observe: true,
                observeParents: true,
                touchAngle: 20,
                paginationClickable: true,
                lazyLoading : true,
                // lazyLoadingInPrevNextAmount: 1,
                paginationBulletRender: function (swipe, index, className) {
                    //    添加导航
                    return '<li class="'+ className +'"><span>'+titArr[index]+'</span><i class="paginationBor"></i></li>'
                },
                onSlideChangeStart: function (swiper) {
                    oIntegralFilter.hide();
                    oIntegralUseIt.hide();
                },
                onSlideChangeEnd: function (swiper) {
                    var oSlidePage = $('.js_thisArea')
                    var index = swiper.activeIndex;
                    presentData.integIndex = index;
                    // console.log(swiper)
                    // console.log(presentData.preTabLoadOff[index])

                    if(presentData.preTabLoadOff[index]){
                        // console.log(presentData.preTabLoadOff[index])
                        // console.log(" postAreaData " + index);
                        presentData.postAreaData(goodsDateUrl[index],presentData.startIntegralArr[index].startIntegral,
                            presentData.endIntegralArr[presentData.preNavIndex].endIntegral,index,0,function () {
                        })
                    }
                    else {
                        // if(presentData.allAreaData[index].length == 0){
                        //
                        //     oSideBox.stop().animate({'right': '-3.5rem'}, 300);
                        // }
                        // var dataGroup = index == 0 ? presentData.dataGroup0 : presentData.dataGroup1
                        if(presentData.allAreaData[index].length == 0 && presentData.dataIndexArr[index] == 0){
                            oIntegralFilter.hide();
                        }else {
                            if(presentData.isIntegralArr[index]  == 1){
                                oIntegralFilter.show();
                            }
                            if(presentData.isIntegralUseIt[index]  == 1){
                                oIntegralUseIt.show();
                            }
                        }
                    }
                    $('.js_scrollMain').find('.js_thisArea').hide().eq(index).show();
                    presentData.preNavIndex = index;

                    _this.SetSession();

                    lazLoading.DestroyLazLoadingImg();
                    lazLoading.AddLazLoadingImg(oSlidePage[index]);
                    // presentFn.HisScrollTop(presentData.integIndex);
                },
            })

            // 设置app产品跳转链接
            myPub.JudgeAppHref($('.js_scrollMain').find('.js_appHref'));
        },


        //    滚动加载
        scrollPage: function () {
            var _this = this;
            // var oScrollMain = $('.js_scrollMain');
            var oScrollMain = $('.js_thisArea');
            var minHeight = 300;
            _this.nHeaderHeight = parseInt(oHeader.outerHeight(true));
            oScrollMain.off('scroll');
            oScrollMain.on('scroll',function () {
                var afterScroll = $(this).scrollTop();
                // console.log('llklklklkl',presentData.prePageSCroll);
                // 滚动页面距离底部300像素 延迟150毫秒加载数据
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function () {
                    // 显示隐藏回到顶部侧边框
                    var index = presentData.preNavIndex;

                    presentData.prePageSCroll[index] = afterScroll;

                    _this.ShowGoTop(afterScroll);
                    if (oScrollMain[index].scrollHeight - afterScroll - oScrollMain.eq(index).height() < minHeight) {
                        // 设置翻页到最后一页 返回
                        presentData.postAreaData(goodsDateUrl[index],presentData.startIntegralArr[presentData.preNavIndex],
                            presentData.endIntegralArr[presentData.preNavIndex].endIntegral,presentData.preNavIndex,presentData.dataIndexArr[index],function () {

                        })
                    }
                },150)
            })
        },
        // 显示回到顶部按钮
        ShowGoTop: function (scrollTop) {
            scrollTop > 300 ? oSideBox.stop().animate({'right': 0}, 300) : oSideBox.stop().animate({'right': '-3.5rem'}, 300);
        },

        //    拼接的html
        presentHtml: function (data, startNum, endNum,smallImgArg300, isShowPoint) {
            var shtml = '';
            for(var i = startNum; i < endNum; i++){
                var priceShow = '';
                if(isShowPoint){
                    if(data[i].salePrice > 0){
                        priceShow =
                            '<span class="goodsPrice integralNum">'+data[i].memberPoint+'</span><span class="integralGrayText">积分</span>'+
                            '<span class="HBox tableCell">'+
                            '    <em class="plusText">+</em><span class="goodsPrice integralNum">' + data[i].salePrice + '</span><span class="integralGrayText">元</span>'+
                            '</span>';
                    } else {
                        priceShow =
                            '<span class="goodsPrice integralNum">'+data[i].memberPoint+'</span><span class="integralGrayText">积分</span>';
                    }
                }else{
                    priceShow =
                        '<span class="HBox tableCell">'+
                        '    <span class="goodsPrice integralNum">' + data[i].salePrice + '</span><span class="integralGrayText">元</span>'+
                        '</span>';
                }
                shtml +='<li>'+
                    '<a class="BoxSelf" href="/h/goodspay/goodsView/'+data[i].goodsSn+'">'+
                    '     <figure>'+
                    '         <img class="lazy js_lazyImg fadeIn" data-echo="' + HTTP_IMAGE_URL+data[i].showImage + smallImgArg300 + '" src="/static_v4/image/loadImg.jpg">';
                if(data[i].goodsLabels && data[i].goodsLabels != ""){
                    shtml += '<div class="verpromotionHot"><span>'+data[i].goodsLabel+'</span><div><img src="/static_v4/image/iconImg/hotIcon.png" alt=""></div></div>'
                }
                shtml += '     </figure>'+
                    '     <aside class="priceArea VBox Bflex1">'+
                    '         <div class="priceArea_name">'+
                    '             <h4>' + data[i].name + '</h4>'+
                    '         </div>'+
                    '         <div class="priceArea_price HBox">'+
                    priceShow +
                    '             </p>'+
                    '         </div>'+
                    '     </aside>'+
                    '</a> '+
                    '</li>';
            }
            return shtml;
        },

        // 没有商品时的显示
        noProductHtml: function () {
            var shtml =  '<div class="errPage VBox">'+
                '   <div class="errImgBox halfImgBox">'+
                '       <figure class="errImg errImgFig">'+
                '           <img src="/static_v4/image/wonderful/goods-null_trans.png" alt="">'+
                '       </figure>'+
                '   </div>'+
                '   <div class="errTxt Bflex1">'+
                '       <p class="needExpect">咦！怎么什么都没有？</p>'+
                '       <p class="jumpHref"><a class="laterCome" href="/home">查看更多商品</a></p>'+
                '   </div>'+
                ' </div>';
            return shtml;
        },


        // 历史数据定位
        HistoryInit : function (fn1, fn2) {
            var _this = this;
            if(sessionStorage.getItem("integNavIndex") != null) {
                presentData.integIndex = sessionStorage.getItem("integNavIndex")*1;
                // _this.tabLoadOff[_this.navIndex] = false;
                // sfddjIndex.SildeNavScrollDis(0, function() {
                presentFn.oSlidePageMain.slideTo(presentData.integIndex, 100);
                // });
                _this.GetSessionData();
                if(fn1) fn1(presentData.integIndex);
            }
            else {
                // _this.tabLoadOff[0] = false;
                if(fn2) fn2();
            }
            // 给导航加上内容，须在导航索引更新之后
            // sfddjIndex.slideNavInit();
        },

        // 历史滚动高度
        HisScrollTop: function (index) {
            var _this = this;
            // console.log('jj--------',presentData.prePageSCroll[index]);
            $('.js_thisArea').eq(index).scrollTop(presentData.prePageSCroll[index]);
        },

        // 设置历史定位
        SetSession: function () {
            var _this = this;
            sessionStorage.setItem( "integNavIndex", JSON.stringify(presentData.integIndex) );
            // sessionStorage.setItem( "pagearr", JSON.stringify(_this.pagearr) );
            // sessionStorage.setItem( "integPageSCroll", JSON.stringify(presentData.prePageSCroll) );
            // sessionStorage.setItem( "dataStore", JSON.stringify(_this.dataStore) );
        },

        // 通过历史数据设置初始数据
        GetSessionData: function() {
            var _this = this;
            // var pageSCrollNum = sessionStorage.getItem("integPageSCroll");
            var pageIndex = sessionStorage.getItem("integNavIndex");
            // console.log('hhhaddd',pageSCrollNum);
            // var dataStoreList = sessionStorage.getItem("dataStore");

            if (pageIndex != null) {
                // 设置页码数
                presentData.integIndex = JSON.parse(pageIndex);
            }

            // if (pageSCrollNum != null) {
            //     // 设置页面滚动数据
            //     presentData.prePageSCroll = JSON.parse(pageSCrollNum);
            // }

            // if (dataStoreList != null) {
            //     // 设置历史商品数据
            //     _this.dataStore = JSON.parse(dataStoreList);
            // }

        },
    }
});